public class BinarySearchTree {

    static class TreeNode {
        public int key;
        public TreeNode left;
        public TreeNode right;

        TreeNode(int key) {
            this.key = key;
        }
    }

    public TreeNode root;

    /**
     * 插入一个元素
     * @param key
     */
    public boolean insert(int key) {
        if(root==null){
            root=new TreeNode(key);
            return true;
        }
        TreeNode cur=root;
        TreeNode parent=null;
        while(cur!=null){
            if(cur.key<key){
                parent=cur;
                cur=cur.right;
            }else if(cur.key>key){
                parent=cur;
                cur=cur.left;
            }else{
                return false;
            }

        }
        if(parent.key>key){
            parent.left=new TreeNode(key);
        }else{
            parent.right=new TreeNode(key);
        }
        return true;
    }
    //查找key是否存在
    public TreeNode search(int key) {
        TreeNode cur=root;
        while(cur!=null){
            if(cur.key<key){
                cur=cur.right;
            }else if(cur.key>key){
                cur=cur.left;
            }else{
                return cur;
            }
        }
      
        return null;
    }
    //删除key的值
    public void remove(int key) {
        TreeNode cur = root;
        TreeNode parent = null;
        while (cur != null) {
            if (cur.key < key) {
                parent = cur;
                cur = cur.right;
            } else if (cur.key > key) {
                parent = cur;
                cur = cur.left;
            } else {
                if (cur.left == null) {
                    if (cur == root) {
                        root = cur.right;
                    } else if (cur == parent.left) {
                        parent.left = cur.right;
                    } else {
                        parent.right = cur.right;
                    }
                } else if (cur.right == null) {
                    if (cur == root) {
                        root = cur.left;
                    } else if (cur == parent.left) {
                        parent.left = cur.left;

                    } else {
                        parent.right = cur.left;
                    }
                } else {
                    TreeNode t = cur.right;
                    TreeNode tp = cur;
                    while (t.left != null) {
                        tp = t;
                        t = t.left;
                    }
                    cur.key = t.key;
                    if ( tp.left==t) {
                        tp.left = t.right;
                    } else {
                        tp.right = t.right;
                    }


                }
                return;
            }
        }
    }



   
}